package aisino

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"io/ioutil"

	"gitee.com/xntk2381/invoice"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
)

func ConvertBatchUpload(item invoice.InvoiceItem) (string, error) {
	classification := fmt.Sprintf(`<?xml version="1.0" encoding="GBK"?><FPXT>
<INPUT>
<GoodsNo>
<GoodsNoVer>%v</GoodsNoVer>
<GoodsTaxNo>%v</GoodsTaxNo>
<TaxPre>%v</TaxPre>
<TaxPreCon>%v</TaxPreCon>
<ZeroTax>%v</ZeroTax>
<CropGoodsNo>%v</CropGoodsNo>
<TaxDeduction>%v</TaxDeduction>
</GoodsNo>
</INPUT>
</FPXT>`, item.GoodsNoVer, item.GoodsTaxNo, item.TaxPre,
		item.TaxPreCon, item.ZeroTax, item.CropGoodsNo, item.TaxDeduction)
	res, err := Utf8ToGbk([]byte(classification))
	if err != nil {
		return "", err
	}

	cipherClassification := base64.StdEncoding.EncodeToString(res)
	return fmt.Sprintf(`<?xml version="1.0" encoding="GBK"?>
<FPXT_COM_INPUT>
<ID>1100</ID>
<DATA>%s</DATA>
</FPXT_COM_INPUT>`, cipherClassification), nil
}

// GBK 转 UTF-8
func GbkToUtf8(s []byte) ([]byte, error) {
	reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewDecoder())
	d, e := ioutil.ReadAll(reader)
	if e != nil {
		return nil, e
	}
	return d, nil
}

// UTF-8 转 GBK
func Utf8ToGbk(s []byte) ([]byte, error) {
	reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewEncoder())
	d, e := ioutil.ReadAll(reader)
	if e != nil {
		return nil, e
	}
	return d, nil
}
